import { login, logout, getInfo } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import defAva from '@/assets/defaultImages/defaultAvatar.jpg';
import { defineStore } from 'pinia';
import { ref } from 'vue';

export interface LoginForm {
  username: string;
  password: string;
  code: string;
  uuid: string;
}

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken());
  const name = ref('');
  const avatar = ref('');
  const roles = ref<string[]>([]);
  const permissions = ref<string[]>([]);

  const loginAction = async (userInfo: LoginForm): Promise<void> => {
    try {
      const res = await login(
        userInfo.username.trim(),
        userInfo.password,
        userInfo.code,
        userInfo.uuid
      );
      setToken(res.token);
      token.value = res.token;
    } catch (err) {
      throw err;
    }
  };

  const getInfoAction = async (): Promise<void> => {
    try {
      const res = await getInfo();
      const user = res.user;
      avatar.value = user.avatar ? import.meta.env.VITE_APP_BASE_API + user.avatar : defAva;
      roles.value = res.roles?.length ? res.roles : ['ROLE_DEFAULT'];
      permissions.value = res.permissions || [];
      name.value = user.userName;
    } catch (err) {
      throw err;
    }
  };

  const logoutAction = async (): Promise<void> => {
    try {
      await logout();
      token.value = '';
      roles.value = [];
      permissions.value = [];
      removeToken();
    } catch (err) {
      throw err;
    }
  };

  return {
    token,
    name,
    avatar,
    roles,
    permissions,
    login: loginAction,
    getInfo: getInfoAction,
    logOut: logoutAction
  };
});
